import { Form, Picker } from 'antd-mobile'
import style from './index.module.less'
import { CloseCircleFill } from 'antd-mobile-icons'
import { useState } from 'react'

const { Item } = Form

function Main ({ label, name, options, rules, formRef, disabled = false, onChange = () => {} }) {
  const [visible, setVisible] = useState(false)
  return (
    <Item
      name={name}
      label={label}
      rules={rules}
      disabled={disabled}
      onClick={() => {
        setVisible(true)
      }}
    >
      <Picker visible={visible} columns={[options]} onCancel={() => setVisible(false)} onConfirm={(v) => {
        const r = v instanceof Array && v.length > 0 ? v[0] : undefined
        formRef.setFieldsValue({ [name]: v });
        setVisible(false)
        onChange(r)
      }} clearable>
        {(value) => {
          return (
            value.length > 0 && value[0] ? (
              <div className={style.picker}>
                <span className={style['picker-inner']}>
                  <span>{value.length > 0 && !!value[0] ? value[0].label : ''}</span>
                </span>
                <span className={style['picker-clear']} onClick={(e) => {
                  e.stopPropagation()
                  formRef.resetFields([name])
                  formRef.validateFields([name])
                  onChange(undefined)
                }}>
                  <CloseCircleFill />
                </span>
              </div>
            ) : (
              <span />
            )
          )
        }}
      </Picker>
    </Item>
  )
}

export default Main
